const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const getToken = _ =>{
  return wx.getStorageSync('auth_token') || ''
}

const setToken = token => {
  wx.setStorageSync('auth_token', token)
}

const baseUrl = 'http://127.0.0.1:5000/api/v1'


const wx_login = _ => {
  wx.login({
    success: res => {
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      wx.request({
        url: baseUrl + '/user/login',
        method: 'post',
        data: {
          code: res.code
        },
        success(res2) {
          let data = res2.data.data
          let header = res2.header
          // 设置user_info
          // 保存token
          setToken(header.brear_wx_token)
          console.log(data)
        }
      })
    }
  })
}

// flask-restful 对application/json 的get请求支持不好
// 不使用get请求，统一用get
const http_get = (url, data, done) => {
  console.log(data)
  wx.request({
    url: baseUrl + url,
    method: 'GET',
    header: {
      'brear_wx_token': getToken()
    },
    success: done,
    fail(res) {
      console.error(res)
    }
  })
}

const  http_post = (url, data, done) => {
  wx.request({
    url: baseUrl + url,
    data: data,
    method: 'POST',
    header: {
      'content-type': 'application/json', // 默认值
      'brear_wx_token': getToken()
    },
    success: res => {
      if (res_deal(res)){
        done(res)
      }
    },
    fail(res) {
      console.error(res)
    }
  })
}

const res_deal = (res) => {
  if (res.statusCode === 202) {
    console.log(res)
    console.log('no_login')
    return null
  }
  else {
    return res.data
  }
}

module.exports = {
  formatTime: formatTime,
  http_post: http_post,
  getToken: getToken,
  wx_login: wx_login,
}
